<!-- canvas实现流星雨 -->
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
let arr = ref<any[]>([])
class Star {
  x: number
  y: number
  text: string
  color: string
  constructor() {
    this.x = 700 * Math.random()
    this.y = 500 * Math.random()
    this.text = '.'
    this.color = 'white'
  }
  /**
   * 获取颜色
   */
  getColor() {
    let _r = Math.random()
    if (_r < 0.5) {
      this.color = '#333'
    } else {
      this.color = 'white'
    }
  }
  /**
   * 初始化
   */
  init() {
    // this.getColor()
  }
  /**
   * 绘制
   */
  draw(context: any) {
    context.fillStyle = this.color
    context.fillText(this.text, this.x, this.y)
  }
}

const starCount = 300
let context: any

onMounted(() => {
  context = document.getElementById('meteor-shower')
  context = context?.getContext('2d')
  context?.fillRect(0, 0, 700, 500)
  drawStar()
  playStars()
})

/**
 * 画星星
 */
const drawStar = () => {
  for (let index = 0; index < starCount; index++) {
    let star = new Star()
    star.init()
    star.draw(context)
    arr.value.push(star)
  }
}

let t1 = 0
const playStars = () => {
  for (let index = 0; index < starCount; index++) {
    arr.value[index].getColor()
    arr.value[index].draw(context)
  }
  t1 = requestAnimationFrame(playStars)
}
</script>

<template>
  <div>
    <canvas id="meteor-shower"></canvas>
  </div>
</template>

<style lang="scss" scoped>
#meteor-shower {
  width: 700px;
  height: 500px;
}
</style>
